//
//  NSObject+GLArchive.m
//  HGLRunTime
//
//  Created by huang long on 16/12/10.
//  Copyright © 2016年 huang gu long. All rights reserved.
//

#import "NSObject+GLArchive.h"
#import <objc/runtime.h>
@implementation NSObject (GLArchive)


+ (NSArray *)propertys{
    unsigned int count;
    
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    NSMutableArray *properNames = [NSMutableArray array];
    
    for (int i = 0; i < count; i ++) {
        Ivar ivar = ivarList[i];
        
        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
        
        [properNames addObject:name];
        
    }
    
    return properNames;
}


- (void)encodeWithCoder:(NSCoder *)coder
{
    NSArray *propertys = [[self class] propertys];
    for (NSString * propertyName in propertys) {
        id m = [self valueForKey:propertyName];
        if ([m isKindOfClass:[NSObject class]]) {
            [coder encodeObject:m forKey:propertyName];
        }
    }
    
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [self init]) {
        NSArray *propertys = [[self class] propertys];
        for (NSString * propertyName in propertys) {
            id m = [aDecoder decodeObjectForKey:propertyName];
            if (m) {
                [self setValue:m forKey:propertyName];
            }
        }
        
    }
    return self;
}


- (id)valueForUndefinedKey:(NSString *)key{
    return nil;
}

@end
